<?php
/**
 * 上传Kol
 * User: bgl
 * Date: 2022/9/7
 * Time: 16:44
 */

namespace App\Admin\Controllers\KolManage;

use App\Importer\Basics\BImporter;
use App\Models\Basics\SysCountry;
use App\Models\KolManage\Kol;
use App\Models\KolManage\KolOrder;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class KolOrderUploadController extends AdminController{

    protected $title = 'Kol订单上传';

    protected function grid()
    {
        $type = request('type');
        return view("kol-manage.kol-order.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importCreate(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(), $file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;

            foreach($data as $row){
                $count++;
                $orderNo    = $row[0] ? trim($row[0]) : '';
                $kolCode      = $row[1] ? trim($row[1]) : '';
                $remark     = $row[2] ? trim($row[2]) : '';

                if(!$orderNo || !$kolCode){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                $reCount = KolOrder::query()
                    ->where('order_no', $orderNo)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = '['.$orderNo.'],系统已存在该订单号，需要更新请前往更新';
                    continue;
                }

                DB::beginTransaction();
                $obj = KolOrder::query()->create([
                    'order_no' => $orderNo,
                    'kol_code' => $kolCode,
                    'remark'   => $remark,
                    'admin_id' => $userId,
                ]);
                if($obj){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true, 'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false, 'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
